<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
      <ion-title>event list</ion-title>
      </ion-toolbar>
      <ion-toolbar >
      <ion-searchbar v-model="searchQuery" :debounce="500" @ionInput="handleInput($event)" ></ion-searchbar>
      </ion-toolbar>      
    </ion-header>
    <ion-content >
      <span>&nbsp;</span>Update at:{{ data }}
        <ion-card class="card" v-for="item in items" :key="item.id" :style="{ backgroundColor: getCardColor(item.triggerTelescopeName) }" button @click="goToDetail(item.triggerName)">
          <ion-card-header >
            <ion-card-title class="space-between">{{ item.triggerName }}<span class="spacer"></span>{{ item. triggerTelescopeName}}</ion-card-title>            
            <!-- <ion-card-subtitle>Update at:{{ data }}</ion-card-subtitle> -->
          </ion-card-header>        
          <ion-card-content class="list" >
               <ion-grid>
                <ion-row>
                  <ion-col size="12"  @click="openExternalPage">triggerId:{{ item.triggerId }} </ion-col>
                  <ion-col size="12">EVENT NAME:{{ item.eventName }} </ion-col>
                  <ion-col size="12">TIME:{{ item.triggerTime }}
                    <ion-icon  aria-hidden="true" :icon="helpCircleOutline" button @click="showTooltip = true">
                      <ion-popover :is-open="showTooltip" @didDismiss="showTooltip = false" >
                        <ion-content class="ion-padding">Trigger Time(T0),in UT,is retrived from the latest alert packet.</ion-content>
                      </ion-popover>
                    </ion-icon>
                  </ion-col>
                  <ion-col  size-sm="4" >RA:{{ item.triggerRa }}
                      <ion-icon aria-hidden="true" :icon="helpCircleOutline" button @click="showTooltip1 = true">
                      <ion-popover :is-open="showTooltip1" @didDismiss="showTooltip1 = false">
                        <ion-content class="ion-padding">Coordinates(in J2000 epoch) and Err,are retrived from the latest packet.</ion-content>
                      </ion-popover>
                    </ion-icon>
                    </ion-col>
                  <ion-col size-sm="4">DEC:{{ item.triggerDec }} </ion-col>
                  <ion-col size-sm="4">ERR:{{ convertToDegMin(item.triggerErr) }} </ion-col>
                </ion-row>                
               </ion-grid>               
          </ion-card-content>        
      </ion-card>    
    </ion-content>
  </ion-page>
</template>

<script setup >
import { useRouter } from 'vue-router';
const router = useRouter();
import { IonPage,
          IonCard,
          IonPopover,
          IonCardContent,
          IonCardHeader,
          IonIcon,
          IonCardTitle,
          IonGrid, 
          IonCol, 
          IonRow, 
          IonContent,
          IonToolbar,
          IonTitle,
          IonHeader,
          IonSearchbar,
          
          // IonList,
          //  IonItem,
          } from '@ionic/vue';
import { helpCircleOutline } from 'ionicons/icons';
import service from '@/api/api'
import { ref } from 'vue';
import { onMounted } from 'vue';

const showTooltip = ref(false);
const showTooltip1 = ref(false);
const convertToDegMin = (triggerErr) => {
  if(triggerErr!==null){
   const minutes = Math.floor(triggerErr * 60);
  return ` ${minutes.toFixed()}`;
  // return ((triggerErr) * 60 * Math.PI).toFixed(2);
  }
  
};
const searchQuery = ref('');
const item=[{triggerTelescopeName:'',
  triggerId:'',
  eventName: '',
  triggerName: '',
  triggerTime: '',
  triggerRa: '',
  triggerDec: '',
  triggerErr: '',
  data:'',
  cls:'',
  id:''}] 
const data=ref('')   
const items=ref(item)
   const fetchData =async () => {
      try {       
        const response = await service.post('/alertApi/getTriggers',{length:100});
        const response1 = await service.get('/alertApi/getLastTime');
        items.value = response.data.data.list;
        data.value= response1.data.data;         
          console.log(response.data);
      } catch (error) {
        // 处理请求错误
        console.error('Error fetching data:',error);
      }
    }    
    onMounted(fetchData);
    
    const goToDetail = (triggerName) => {
      router.push({
      name: 'eventdetails',
      params: { triggerName }, 
    });
  };
  const openExternalPage = () => {
  const url = 'https://www.svom.cn/BA/#/BACenter/Event/Detail?triggerId=4036'; 
  window.open(url, '_blank'); // 使用'_blank'打开新窗口或标签页
};
  

  
  const getCardColor = (triggerTelescopeName) => {
  switch (triggerTelescopeName) {
    case 'SVOM':
      return '	PapayaWhip';
    case 'Fermi':
      return '		Honeydew';
    default:
      return 'Ivory';
  }
};
onMounted(() => {
  setInterval(() => {
    // 刷新页面的逻辑，例如重新请求数据
    doRefresh();
  }, 60000);
  console.log('页面刷新');
});

// 刷新事件处理函数
async function doRefresh() {
  await fetchData(); // 获取最新数据
  // item.detail.complete(); // 刷新完成
}

// watch(searchQuery, (newQuery) => {
//   items.value = items.value.filter((item: {triggerTelescopeName: string }) =>
//     item.triggerTelescopeName.toLowerCase().includes(newQuery.toLowerCase())  
//   );
// });
const handleInput = (event ) => {
        console.log('被触发',event)
        const query = event.target.value.toLowerCase();
        items.value = items.value.filter((item) =>
    item.triggerName.toLowerCase().indexOf(query)> -1 || item.triggerTelescopeName.toLowerCase().indexOf(query)> -1);
    if (searchQuery.value === '') {
    // 当搜索框为空时，重置列表
    fetchData();
  }
  }
  
 


</script>

<style scoped>

  ion-col {
    /* color: #1c1b1b; */
    text-align: center;
  }
 .list{
  text-align: center;
 }
  ion-title{
    text-align: center;
  }
  .card {
  font-family: 'Arial', sans-serif; /* 设置卡片内的字体为Arial */
}
.space-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
 
.spacer {
  width: 50%; /* 这里的宽度可以根据需要调整，比如25%、33.33%等 */
}
</style>
